package com.yljk.yljkproject.aliyunface;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.zoloz.toyger.ToygerLog;
import com.alipay.zoloz.toyger.face.ToygerFaceAttr;
import com.aliyun.aliyunface.ToygerConst;
import com.aliyun.aliyunface.ToygerConst.*;
import com.aliyun.aliyunface.ToygerPresenter;
import com.aliyun.aliyunface.WorkState;
import com.aliyun.aliyunface.api.ZIMFacade;
import com.aliyun.aliyunface.camera.CameraConstants;
import com.aliyun.aliyunface.camera.CameraSurfaceView;
import com.aliyun.aliyunface.camera.ICameraInterface;
import com.aliyun.aliyunface.config.AndroidClientConfig;
import com.aliyun.aliyunface.config.DeviceSetting;
import com.aliyun.aliyunface.config.OSSConfig;
import com.aliyun.aliyunface.log.RecordLevel;
import com.aliyun.aliyunface.log.RecordService;
import com.aliyun.aliyunface.network.NetworkEnv;
import com.aliyun.aliyunface.network.NetworkPresenter;
import com.aliyun.aliyunface.network.OssClientHelper;
import com.aliyun.aliyunface.network.ZimValidateCallback;
import com.aliyun.aliyunface.network.model.OCRInfo;
import com.aliyun.aliyunface.ui.ToygerWebView;
import com.aliyun.aliyunface.ui.UICustomParams;
import com.aliyun.aliyunface.ui.overlay.CommAlertOverlay;
import com.aliyun.aliyunface.ui.widget.CircleHoleView;
import com.aliyun.aliyunface.ui.widget.RoundProgressBar;
import com.aliyun.aliyunface.ui.widget.RoundProgressCallback;
import com.aliyun.aliyunface.utils.Avatar;
import com.aliyun.aliyunface.utils.MiscUtil;
import com.xiaomi.push.id;
import com.yilijk.base.utils.ALog;
import com.yljk.yljkproject.R;

import net.security.device.api.SecurityDevice;
import net.security.device.api.SecuritySession;
/**
 * Create By shicheng
 *
 * 阿里云人脸识别
 *
 */
public class MyToygerActivity extends AppCompatActivity {
    private final int TG_TIPS_DO_PHOTIUS = 100;
    private CameraSurfaceView mCameraSurfaceView;
    private int faceScanRetryCnt = 0;
    private boolean isActivityPaused = false;
    private ImageView btnClose = null;
    private long faceScanStartTime = System.currentTimeMillis();
    private Handler uiHandler = new Handler(new Handler.Callback() {
        public boolean handleMessage(Message msg) {
            switch(msg.what) {
                case 901:
                    MyToygerActivity.this.onSurfaceChanged((double)msg.arg1, (double)msg.arg2);
                    break;
                case 902:
                    MyToygerActivity.this.onFaceComplete();
                    break;
                case 903:
                    MyToygerActivity.this.onErrorCode((String)msg.obj);
                    break;
                case 904:
                    MyToygerActivity.this.showFaceTips(msg.arg1);
                    break;
                case 905:
                    MyToygerActivity.this.onGuidAuth();
                    break;
                case 906:
                    MyToygerActivity.this.onGuidClose();
                    break;
                case 907:
                    MyToygerActivity.this.onGuidLog((String)msg.obj);
                    break;
                case 908:
                    MyToygerActivity.this.onGuidLoadLocal();
                case 909:
                default:
                    break;
                case 910:
                    MyToygerActivity.this.retryFaceScan();
                    break;
                case 911:
                    MyToygerActivity.this.onStartPhotinus();
                    break;
                case 912:
                    MyToygerActivity.this.onChangePhotinusColor(msg);
                    break;
                case 913:
                    MyToygerActivity.this.onStartLoading();
            }

            return true;
        }
    });
    private WorkState prevWorkState = null;

    public MyToygerActivity() {
    }

    private void onStartLoading() {
        this.showAvatar(true);
        this.startFaceUploadProcess();
    }

    private void onChangePhotinusColor(Message msg) {
        int photinusColor = msg.arg1;
        LinearLayout mainPage = (LinearLayout)this.findViewById(R.id.toyger_main_page);
        if (null != mainPage) {
            mainPage.setBackgroundColor(photinusColor);
        }

        CircleHoleView cirleHoleView = (CircleHoleView)this.findViewById(R.id.toyger_face_circle_hole_view);
        if (null != cirleHoleView) {
            cirleHoleView.changeBackColor(photinusColor);
        }

    }

    private void onStartPhotinus() {
        this.hideFaceTips();
    }

    @SuppressLint("WrongConstant")
    private void onGuidLoadLocal() {
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "guidPage", new String[]{"action", "load local page"});
        ToygerWebView toygerWebView = (ToygerWebView)this.findViewById(R.id.guid_web_page);
        if (null != toygerWebView) {
            toygerWebView.setVisibility(0);
            toygerWebView.loadUrl("file:///android_asset/nav/facewelcome.html");
        }

    }

    @SuppressLint("WrongConstant")
    private void onGuidAuth() {
        ToygerWebView toygerWebView = (ToygerWebView)this.findViewById(R.id.guid_web_page);
        if (null != toygerWebView) {
            toygerWebView.setVisibility(8);
        }

        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "guidPage", new String[]{"action", "click auth, and start toyger"});
        this.initToyger();
    }

    private void onGuidClose() {
        this.showMessageBox(R.string.message_box_title_exit_tip, R.string.message_box_message_exit_tip, R.string.message_box_btn_ok_tip, R.string.message_box_btn_cancel_tip, new MyToygerActivity.MessageBoxCB() {
            public void onOK() {
                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "userBack", new String[]{"type", "guidPageClose"});
                MyToygerActivity.this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_USER_BACK);
            }

            public void onCancel() {
            }
        });
    }

    private void onGuidLog(String log) {
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "guidPageLog", new String[]{"guid_log", log});
    }

    private void onFaceComplete() {
        long faceScanElapsed = System.currentTimeMillis() - this.faceScanStartTime;
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScanCost", new String[]{"cost", String.valueOf(faceScanElapsed)});
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScanComplete", new String[]{"status", "face completed"});
        ICameraInterface cameraInterface = this.getCameraInterface();
        if (null != cameraInterface) {
            cameraInterface.stopPreview();
        }

        this.stopFaceScanProcess(true);
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "uploadFaceImage", new String[]{"status", "start upload face image"});
        Bitmap faceImage = ToygerPresenter.getInstance().getHighQualityFaceImage();
        byte[] faceImageBytes = MiscUtil.bitmap2Bytes(faceImage);
        if (null == faceImageBytes) {
            this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_FACE_IMAGE_ERROR);
        } else {
            OSSConfig ossConfig = ToygerPresenter.getInstance().getOssConfig();
            if (null == ossConfig) {
                RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "uploadFaceImageFail", new String[]{"status", "false", "errMsg", "ossConfig is invalid"});
                this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_NET_INIT_ERROR);
            } else {
                OssClientHelper.getInstance().init();
                OssClientHelper.getInstance().addUploadFile(0, ossConfig.BucketName, ossConfig.FileNamePrefix + "_0.jpeg", faceImageBytes);
                if (ToygerPresenter.getInstance().isUsePhotinus()) {
                    byte[] metaFileContent = MiscUtil.readFileContent(ToygerPresenter.getInstance().getPhotinusMetadataFilePath());
                    byte[] videoFileContent = MiscUtil.readFileContent(ToygerPresenter.getInstance().getPhotinusVideoFilePath());
                    if (null != metaFileContent && null != videoFileContent) {
                        OssClientHelper.getInstance().addUploadFile(1, ossConfig.BucketName, MiscUtil.genOssFileName(ossConfig.FileNamePrefix, "colorinfo", "json"), metaFileContent);
                        OssClientHelper.getInstance().addUploadFile(2, ossConfig.BucketName, MiscUtil.genOssFileName(ossConfig.FileNamePrefix, "colorvideo", "mp4"), videoFileContent);
                    } else {
                        ToygerPresenter.getInstance().setUsePhotinus(false);
                    }
                }

                OssClientHelper.getInstance().startUploadFiles(this, ossConfig.OssEndPoint, ossConfig.AccessKeyId, ossConfig.AccessKeySecret, ossConfig.SecurityToken, new OssClientHelper.OssClientUploadListener() {
                    public boolean onUploadSuccess(int idx, String bucketName, String fileName) {
                        return true;
                    }

                    public boolean onUploadError(int idx, String bucketName, String fileName, String errMsg) {
                        RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "ossUploadFileError", new String[]{"idx", "" + idx, "fileName", fileName, "errMsg", errMsg});
                        if ("InvalidAccessKeyId".equalsIgnoreCase(errMsg)) {
                            MyToygerActivity.this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_OSS_TOKEN_INVALID);
                            return false;
                        } else {
                            String errCode = "";
                            if (0 == idx) {
                                errCode = ToygerConst.ZcodeConstants.ZCODE_NET_UPLOAD_IMAGE_ERROR;
                            } else if (1 == idx) {
                                errCode = ToygerConst.ZcodeConstants.ZCODE_NET_UPLOAD_PHOTINUS_META_ERROR;
                            } else if (2 == idx) {
                                errCode = ToygerConst.ZcodeConstants.ZCODE_NET_UPLOAD_PHOTINUS_VIDEO_ERROR;
                            }

                            MyToygerActivity.this.sendErrorCode(errCode);
                            return false;
                        }
                    }

                    public void onFinish(int uploadCnt, int successCnt) {
                        if (uploadCnt == successCnt) {
                            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "ossUploadFileSuccess", new String[]{"count", "" + successCnt});
                            MyToygerActivity.this.onFilesUploadSuccess();
                        }

                    }
                });
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    private void sendErrorCode(String errCode) {
        Message msg = Message.obtain();
        msg.what = 903;
        msg.obj = errCode;
        this.uiHandler.sendMessage(msg);
    }

    private void onFilesUploadSuccess() {
        String zimId = ToygerPresenter.getInstance().getZimId();
        Bitmap faceImage = ToygerPresenter.getInstance().getHighQualityFaceImage();
        ToygerFaceAttr faceAttr = ToygerPresenter.getInstance().getHighQualityFaceAttr();
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "startNetVerify", new String[]{"status", "start net verify"});
        String videoFileMd5 = "";
        if (ToygerPresenter.getInstance().getUseVideo()) {
            MiscUtil.getFileMd5(ToygerPresenter.getInstance().getVideoFilePath());
        }

        String photinusPrefix = "/";
        OSSConfig ossConfig = ToygerPresenter.getInstance().getOssConfig();
        if (null != ossConfig) {
            photinusPrefix = photinusPrefix + ossConfig.BucketName + "/";
        }

        String faceFileName = OssClientHelper.getInstance().getUploadFileName(0);
        String photinusMetaFileName = "";
        String photinusVideoFileName = "";
        if (ToygerPresenter.getInstance().isUsePhotinus()) {
            photinusMetaFileName = photinusPrefix + OssClientHelper.getInstance().getUploadFileName(1);
            photinusVideoFileName = photinusPrefix + OssClientHelper.getInstance().getUploadFileName(2);
        }

        OCRInfo ocrInfo = ToygerPresenter.getInstance().getOcrInfo();
        NetworkEnv networkEnv = ToygerPresenter.getInstance().getNetworkEnv();
        if (null == networkEnv) {
            this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_SYSTEM_EXC);
        } else {
            String metaInfo = ZIMFacade.getMetaInfos(this);
            NetworkPresenter.zimValidate(networkEnv, zimId, metaInfo, faceFileName, photinusMetaFileName, photinusVideoFileName, faceImage, faceAttr, videoFileMd5, ocrInfo, new ZimValidateCallback() {
                public void onSuccess() {
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "netVerifyRes", new String[]{"status", "success", "verify", "success"});
                    MyToygerActivity.this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_NET_VERIFY_SUCCESS);
                }

                public void onValidateFail(String retCodeSub, String retMessageSub, String srvRes) {
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "netVerifyRes", new String[]{"status", "success", "verify", "false", "msg", "Face Compare onValidateFail, retCodeSub=" + retCodeSub + " retMessageSub=" + retMessageSub + " srvRes=" + srvRes});
                    MyToygerActivity.this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_VERIFY_FAIL_PREFIX + retCodeSub);
                }

                public void onServerError(String code, String errMsg) {
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "netVerifyRes", new String[]{"status", "fail", "msg", "Server Internal onError, code=" + code + " errMsg=" + errMsg});
                    MyToygerActivity.this.sendErrorCode(code);
                }

                public void onError(String code, String errMsg) {
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_ERROR, "netVerifyRes", new String[]{"status", "fail", "msg", "Face Compare onError, code=" + code + " errMsg=" + errMsg});
                    MyToygerActivity.this.sendErrorCode(ToygerConst.ZcodeConstants.ZCODE_NET_VERIFY_ERROR);
                }
            });
        }
    }

    private void onErrorCode(String errCode) {
        if (TextUtils.isEmpty(errCode)) {
            errCode = ToygerConst.ZcodeConstants.ZCODE_SYSTEM_EXC;
        }

        this.stopFaceScanProcess(true);
        this.stopFaceUploadProcess();
        if (ToygerPresenter.getInstance().isUseMsgBox()) {
            String finalErrCode = errCode;
            boolean hasShow = this.showErrorMsgBox(errCode, new MyToygerActivity.MessageBoxCB() {
                public void onOK() {
                    MyToygerActivity.this.sendResponseAndFinish(finalErrCode);
                }

                public void onCancel() {
                }
            });
            if (!hasShow) {
                this.sendResponseAndFinish(errCode);
            }
        } else {
            this.sendResponseAndFinish(errCode);
        }

    }

    private void sendResponseAndFinish(String errCode) {
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "MyToygerActivityClose", new String[]{"errCode", errCode});
        this.finish();
        ToygerPresenter.getInstance().sendResAndExit(errCode);
    }

    private boolean showErrorMsgBox(String errCode, MyToygerActivity.MessageBoxCB msgboxCb) {
        ToygerLog.e("showErrorMsgBox=>" + errCode);
        if (!errCode.equalsIgnoreCase(ToygerConst.ZcodeConstants.ZCODE_NET_INIT_ERROR) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_NET_UPLOAD_IMAGE_ERROR) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_NET_VERIFY_ERROR) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_NETWORK_TIMEOUT) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_NETWORK_ERROR)) {
            if (!errCode.equalsIgnoreCase(ToygerConst.ZcodeConstants.ZCODE_INIT_TOYGER_ERROR) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_LIVENESS_ERROR) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_MODEL_LOAD_ERROR)) {
                if (!errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_ERROR_CAMERA_NO_DEVICE) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_ERROR_CAMERA_OPEN_FAILED) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_ERROR_CAMERA_STREAM_ERROR) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_NO_FRANT_CAMERA) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_OS_VERSION_LOW) && !errCode.equalsIgnoreCase(ZcodeConstants.ZCODE_UNSUPPORTED_CPU)) {
                    return false;
                } else {
                    this.showMessageBox(R.string.message_box_title_not_support, R.string.message_box_message_not_support, R.string.message_box_btn_ok_tip, -1, msgboxCb);
                    return true;
                }
            } else {
                this.showMessageBox(R.string.message_box_title_sys_error, R.string.message_box_message_sys_error, R.string.message_box_btn_ok_tip, -1, msgboxCb);
                return true;
            }
        } else {
            this.showMessageBox(R.string.message_box_title_network, R.string.message_box_message_network, R.string.message_box_btn_ok_tip, -1, msgboxCb);
            return true;
        }
    }

    @SuppressLint("WrongConstant")
    private void hideFaceTips() {
        TextView tipText = (TextView)this.findViewById(R.id.messageCode);
        if (null != tipText) {
            tipText.setVisibility(4);
        }

    }

    private void showFaceTips(int faceCode) {
        String prompt = "";
        switch(faceCode) {
            case 1:
                prompt = this.getString(R.string.no_face);
                break;
            case 2:
                prompt = this.getString(R.string.distance_too_far);
                break;
            case 3:
                prompt = this.getString(R.string.distance_too_close);
                break;
            case 4:
                prompt = this.getString(R.string.face_not_in_center);
                break;
            case 5:
            case 6:
                prompt = this.getString(R.string.bad_pitch);
                break;
            case 7:
                prompt = this.getString(R.string.is_moving);
                break;
            case 8:
                prompt = this.getString(R.string.bad_brightness);
                break;
            case 9:
                prompt = this.getString(R.string.bad_quality);
                break;
            case 10:
                prompt = this.getString(R.string.bad_eye_openness);
                break;
            case 11:
                prompt = this.getString(R.string.blink_openness);
                break;
            case 12:
                prompt = this.getString(R.string.stack_time);
                break;
            case 100:
                prompt = this.getString(R.string.topText_do_photinus);
        }

        TextView tipText = (TextView)this.findViewById(R.id.messageCode);
        if (null != tipText && !TextUtils.isEmpty(prompt)) {
            tipText.setText(prompt);
        }

    }

    private void retryFaceScan() {
        this.startFaceScanProcess(new RoundProgressCallback() {
            public void onProgress(int progress) {
            }

            public void onFinish() {
                WorkState workState = ToygerPresenter.getInstance().getWorkState();
                if (WorkState.FACE_COMPLETED != workState && WorkState.PHOTINUS != workState) {
                    if (MyToygerActivity.this.faceScanRetryCnt >= 4) {
                        MyToygerActivity.this.showMessageBox(R.string.message_box_title_retry_face_scan_time_out, R.string.message_box_message_retry_face_scan_time_out, R.string.message_box_message_btn_retry_ok_time_out, -1, new MyToygerActivity.MessageBoxCB() {
                            public void onOK() {
                                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScan", new String[]{"status", "time out, not success"});
                                MyToygerActivity.this.sendErrorCode(ZcodeConstants.ZCODE_OVER_TIME);
                            }

                            public void onCancel() {
                            }
                        });
                    } else {
                        int titleOperFail = R.string.message_box_title_retry_face_scan;
                        if (MyToygerActivity.this.isActivityPaused) {
                            titleOperFail = R.string.message_box_title_operation_fail;
                        }

                        MyToygerActivity.this.showMessageBox(titleOperFail, R.string.message_box_message_retry_face_scan, R.string.message_box_btn_retry_ok, -1, new MyToygerActivity.MessageBoxCB() {
                            public void onOK() {
                                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScan", new String[]{"status", "time out, user retry:" + MyToygerActivity.this.faceScanRetryCnt});
                                MyToygerActivity.this.faceScanRetryCnt++;
                                MyToygerActivity.this.uiHandler.sendEmptyMessage(910);
                            }

                            public void onCancel() {
                                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScan", new String[]{"status", "time out, user back"});
                                MyToygerActivity.this.sendErrorCode(ZcodeConstants.ZCODE_OVER_TIME);
                            }
                        });
                    }

                }
            }
        });
    }

    private void onSurfaceChanged(double previewWidth, double previewHeight) {
        ALog.e("Toyger", "surfaceChanged, w=" + previewWidth + " h=" + previewHeight);
        if (this.mCameraSurfaceView != null) {
            if (previewWidth <= previewHeight) {
                this.onPortUIInit(previewWidth, previewHeight);
            } else {
                this.onLandUIInit(previewWidth, previewHeight);
            }
        }

    }

    private void onPortUIInit(double previewWidth, double previewHeight) {
        double cameraSurfaceViewRate = 0.6600000262260437D;
        View screenFrameView = this.findViewById(R.id.screen_main_frame);
        if (null != screenFrameView) {
            int screenW = screenFrameView.getWidth();
            FrameLayout scanFrameView = (FrameLayout)this.findViewById(R.id.toger_main_scan_frame);
            ViewGroup.LayoutParams layoutParams = scanFrameView.getLayoutParams();
            layoutParams.width = (int)(cameraSurfaceViewRate * (double)screenW);
            layoutParams.height = (int)((double)layoutParams.width / (previewWidth * 1.0D) * previewHeight);
            scanFrameView.setLayoutParams(layoutParams);
            CircleHoleView circleHoleView = (CircleHoleView)this.findViewById(R.id.toyger_face_circle_hole_view);
            if (null != circleHoleView) {
                ViewGroup.LayoutParams circleLayoutParams = circleHoleView.getLayoutParams();
                circleLayoutParams.width = layoutParams.width;
                circleLayoutParams.height = layoutParams.height;
                circleHoleView.setLayoutParams(circleLayoutParams);
                circleHoleView.widthAttr = (float)layoutParams.width;
                circleHoleView.heightAttr = (float)layoutParams.width;
                circleHoleView.invalidate();
            }

            RoundProgressBar roundProgressBar = (RoundProgressBar)this.findViewById(R.id.scan_progress);
            if (null != roundProgressBar) {
                ViewGroup.LayoutParams progressBarLayoutParams = roundProgressBar.getLayoutParams();
                progressBarLayoutParams.width = layoutParams.width;
                progressBarLayoutParams.height = layoutParams.width;
                roundProgressBar.setLayoutParams(progressBarLayoutParams);
            }

            TextView messageCodeView = (TextView)this.findViewById(R.id.messageCode);
            if (null != messageCodeView) {
                ViewGroup.LayoutParams messageCodeLayoutParams = messageCodeView.getLayoutParams();
                messageCodeLayoutParams.width = layoutParams.width;
                messageCodeView.setLayoutParams(messageCodeLayoutParams);
            }

            ImageView imageAvatar = (ImageView)this.findViewById(R.id.faceAvatar);
            if (null != imageAvatar) {
                ViewGroup.LayoutParams avatarLayoutParams = imageAvatar.getLayoutParams();
                avatarLayoutParams.width = layoutParams.width;
                avatarLayoutParams.height = layoutParams.width;
                imageAvatar.setLayoutParams(avatarLayoutParams);
            }

            ToygerLog.e("屏幕宽度=>" + screenW + " 预览宽度=>" + layoutParams.width);
        }

        this.mCameraSurfaceView.setBackgroundColor(0);
    }

    private void onLandUIInit(double previewWidth, double previewHeight) {
        double cameraSurfaceViewRate = 0.6600000262260437D;
        View screenFrameView = this.findViewById(R.id.screen_main_frame);
        if (null != screenFrameView) {
            int screenH = screenFrameView.getHeight();
            double mainScanFrameTopMargin = (double)this.getResources().getDimension(R.dimen.comm_margin_size_60);
            FrameLayout scanFrameView = (FrameLayout)this.findViewById(R.id.toger_main_scan_frame);
            ViewGroup.LayoutParams layoutParams = scanFrameView.getLayoutParams();
            layoutParams.height = (int)(cameraSurfaceViewRate * ((double)screenH - mainScanFrameTopMargin));
            layoutParams.width = (int)((double)layoutParams.height / (previewHeight * 1.0D) * previewWidth);
            scanFrameView.setLayoutParams(layoutParams);
            CircleHoleView circleHoleView = (CircleHoleView)this.findViewById(R.id.toyger_face_circle_hole_view);
            if (null != circleHoleView) {
                ViewGroup.LayoutParams circleHoleLayoutParams = circleHoleView.getLayoutParams();
                circleHoleLayoutParams.width = layoutParams.width;
                circleHoleLayoutParams.height = layoutParams.height;
                circleHoleView.setLayoutParams(circleHoleLayoutParams);
                circleHoleView.widthAttr = (float)layoutParams.height;
                circleHoleView.heightAttr = (float)layoutParams.height;
                circleHoleView.invalidate();
            }

            ImageView imageAvatar = (ImageView)this.findViewById(R.id.faceAvatar);
            if (null != imageAvatar) {
                ViewGroup.LayoutParams avatarLayoutParams = imageAvatar.getLayoutParams();
                avatarLayoutParams.width = layoutParams.height;
                avatarLayoutParams.height = layoutParams.height;
                imageAvatar.setLayoutParams(avatarLayoutParams);
            }

            TextView txtMessageCode = (TextView)this.findViewById(R.id.messageCode);
            if (null != txtMessageCode) {
                ViewGroup.LayoutParams txtLayoutParams = txtMessageCode.getLayoutParams();
                txtLayoutParams.width = layoutParams.height;
                txtMessageCode.setLayoutParams(txtLayoutParams);
            }

            RoundProgressBar roundProgressBar = (RoundProgressBar)this.findViewById(R.id.scan_progress);
            if (null != roundProgressBar) {
                ViewGroup.LayoutParams roundLayoutParams = roundProgressBar.getLayoutParams();
                roundLayoutParams.width = layoutParams.height;
                roundLayoutParams.height = layoutParams.height;
                roundProgressBar.setLayoutParams(roundLayoutParams);
            }

            ToygerLog.e("屏幕宽度=>" + screenH + " 预览宽度=>" + layoutParams.height);
        }

        this.mCameraSurfaceView.setBackgroundColor(0);
    }

    public void onResume() {
        super.onResume();
        this.isActivityPaused = false;
    }

    public void onPause() {
        super.onPause();
        this.isActivityPaused = true;
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_my_toyger);
        if (!TextUtils.isEmpty(UICustomParams.TOP_TIP_TEXT)) {
            TextView topTipText = (TextView)this.findViewById(R.id.top_tip_firm_text);
            if (null != topTipText) {
                topTipText.setTextSize(this.getResources().getDimension(R.dimen.comm_normal_small2_font_size));
                topTipText.setText(UICustomParams.TOP_TIP_TEXT);
            }
        }
        TextView title = findViewById(R.id.webviewtitle);
        title.setText("人脸识别");
        MiscUtil.setActivityScreenBrightness(this, 1.0F);

        try {
            (new Thread(new Runnable() {
                public void run() {
                    SecuritySession securitySession = SecurityDevice.getInstance().getSession();
                    if (10000 == securitySession.code) {
                        ToygerPresenter.getInstance().setAliyunDeviceToken(securitySession.session);
                    }

                }
            })).start();
        } catch (Exception var3) {
        }

        this.btnClose = (ImageView) this.findViewById(R.id.web_back);
        if (null != this.btnClose) {
            this.btnClose.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    if (!MyToygerActivity.this.isMessageBoxShow()) {
                        MyToygerActivity.this.showMessageBox(R.string.message_box_title_exit_tip, R.string.message_box_message_exit_tip, R.string.message_box_btn_ok_tip, R.string.message_box_btn_cancel_tip, new MyToygerActivity.MessageBoxCB() {
                            public void onOK() {
                                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "userBack", new String[]{"type", "pressCloseButton"});
                                MyToygerActivity.this.sendErrorCode(ZcodeConstants.ZCODE_USER_BACK);
                            }

                            public void onCancel() {
                            }
                        });
                    }
                }
            });
        }

        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "MyToygerActivityStart", new String[]{"name", "MyToygerActivity"});
        this.initToygerUI();
    }

    @SuppressLint("WrongConstant")
    private void showAvatar(boolean show) {
        ImageView imageView = (ImageView)this.findViewById(R.id.faceAvatar);
        RoundProgressBar roundProgressBar = (RoundProgressBar)this.findViewById(R.id.scan_progress);
        if (null != imageView && null != roundProgressBar) {
            if (!show) {
                imageView.setVisibility(8);
                roundProgressBar.setVisibility(0);
            } else {
                imageView.setVisibility(0);
                roundProgressBar.setVisibility(8);
                Bitmap faceImage = ToygerPresenter.getInstance().getHighQualityFaceImage();
                ToygerFaceAttr toygerFaceAttr = ToygerPresenter.getInstance().getHighQualityFaceAttr();
                Bitmap avatar = Avatar.genAvatar(faceImage, toygerFaceAttr);
                if (null != avatar) {
                    imageView.setImageBitmap(avatar);
                }
            }
        }

    }

    @SuppressLint("WrongConstant")
    private void initToygerUI() {
        AndroidClientConfig androidClientConfig = ToygerPresenter.getInstance().getAndroidClientConfig();
        boolean isGuidEnable = false;
        if (null != androidClientConfig && null != androidClientConfig.getNavi() && androidClientConfig.getNavi().isEnable()) {
            String url = androidClientConfig.getNavi().getUrl();
            if (!TextUtils.isEmpty(url)) {
                ToygerWebView toygerWebView = (ToygerWebView)this.findViewById(R.id.guid_web_page);
                if (null != toygerWebView) {
                    toygerWebView.setVisibility(0);
                    toygerWebView.setHandler(this.uiHandler);
                    toygerWebView.loadUrl(url);
                    isGuidEnable = true;
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "initToygerUI", new String[]{"startGuid", "true", "url", url});
                }
            }
        }

        if (!isGuidEnable) {
            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "initToygerUI", new String[]{"startGuid", "false"});
            this.initToyger();
        }

    }

    @SuppressLint("WrongConstant")
    private void initToyger() {
        this.showAvatar(false);
        RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScan", new String[]{"status", "start preview"});
        LinearLayout toygerMainPage = (LinearLayout)this.findViewById(R.id.toyger_main_page);
        if (null != toygerMainPage) {
            toygerMainPage.setVisibility(0);
        }

        ImageView btnClose = (ImageView) this.findViewById(R.id.web_back);
        if (null != btnClose) {
            btnClose.setVisibility(0);
        }

        ToygerPresenter toygerPresenter = ToygerPresenter.getInstance();
        if (null != toygerPresenter) {
            this.mCameraSurfaceView = (CameraSurfaceView)this.findViewById(R.id.cameraSurfaceView);
            this.mCameraSurfaceView.setVisibility(0);
            CameraConstants.CAMERA_MAX_WIDTH = 600;
            this.mCameraSurfaceView.init(this, true, true, (DeviceSetting[])null);
            this.mCameraSurfaceView.setCameraCallback(toygerPresenter);
            if (!toygerPresenter.init(this, this.uiHandler, this.mCameraSurfaceView.getCameraInterface())) {
                RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScan", new String[]{"status", "init toyger presenter fail"});
                this.sendErrorCode(ZcodeConstants.ZCODE_INIT_TOYGER_ERROR);
                return;
            }

            RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "faceScan", new String[]{"status", "faceScan init Success"});
            this.faceScanRetryCnt = 0;
            this.faceScanStartTime = System.currentTimeMillis();
            this.retryFaceScan();
        }

    }

    private void pauseFaceScanProcess(boolean pause) {
        RoundProgressBar roundProgressBar = (RoundProgressBar)this.findViewById(R.id.scan_progress);
        if (null != roundProgressBar) {
            roundProgressBar.pauseProcess(pause);
        }

        if (pause) {
            this.prevWorkState = ToygerPresenter.getInstance().setWorkState(WorkState.PAUSE);
        } else {
            ToygerPresenter.getInstance().setWorkState(this.prevWorkState);
        }

    }

    private void startFaceScanProcess(RoundProgressCallback roundProgressCallback) {
        RoundProgressBar roundProgressBar = (RoundProgressBar)this.findViewById(R.id.scan_progress);
        if (null != roundProgressBar) {
            int time = 20;
            AndroidClientConfig androidClientConfig = ToygerPresenter.getInstance().getAndroidClientConfig();
            if (null != androidClientConfig && null != androidClientConfig.getColl()) {
                int srvTime = androidClientConfig.getColl().getTime();
                if (srvTime > 0) {
                    time = srvTime;
                }
            }

            if (null != UICustomParams.FACE_PROGRESS_COLOR) {
                roundProgressBar.setGradientColor(Color.parseColor(UICustomParams.FACE_PROGRESS_COLOR));
            }

            roundProgressBar.startProcess(time * 1000, roundProgressCallback);
        }

    }

    private void stopFaceScanProcess(boolean restProgress) {
        RoundProgressBar roundProgressBar = (RoundProgressBar)this.findViewById(R.id.scan_progress);
        if (null != roundProgressBar) {
            roundProgressBar.stopProcess();
            if (restProgress) {
                roundProgressBar.setProgress(0);
            }
        }

    }

    @SuppressLint("WrongConstant")
    private void startFaceUploadProcess() {
        LinearLayout loadingPage = (LinearLayout)this.findViewById(R.id.toyger_face_eye_loading_page);
        if (null != loadingPage) {
            if (loadingPage.getVisibility() == 0) {
                return;
            }

            loadingPage.setVisibility(0);
        }

        ImageView btnClose = (ImageView) this.findViewById(R.id.web_back);
        if (null != btnClose) {
            btnClose.setEnabled(false);
        }

    }

    @SuppressLint("WrongConstant")
    private void stopFaceUploadProcess() {
        LinearLayout loadingPage = (LinearLayout)this.findViewById(R.id.toyger_face_eye_loading_page);
        if (null != loadingPage) {
            loadingPage.setVisibility(8);
        }

        ImageView btnClose = (ImageView) this.findViewById(R.id.web_back);
        if (null != btnClose) {
            btnClose.setEnabled(true);
        }

    }

    protected void onDestroy() {
        ToygerPresenter.getInstance().onRelease();
        OssClientHelper.getInstance().release();
        this.stopFaceScanProcess(true);
        super.onDestroy();
    }

    private ICameraInterface getCameraInterface() {
        return null != this.mCameraSurfaceView ? this.mCameraSurfaceView.getCameraInterface() : null;
    }

    @SuppressLint("WrongConstant")
    public boolean isMessageBoxShow() {
        CommAlertOverlay commAlertOverlay = (CommAlertOverlay)this.findViewById(R.id.message_box_overlay);
        if (null != commAlertOverlay) {
            return commAlertOverlay.getVisibility() == 0;
        } else {
            return false;
        }
    }

    public void onBackPressed() {
        if (!this.isMessageBoxShow()) {
            this.showMessageBox(R.string.message_box_title_exit_tip, R.string.message_box_message_exit_tip, R.string.message_box_btn_ok_tip, R.string.message_box_btn_cancel_tip, new MyToygerActivity.MessageBoxCB() {
                public void onOK() {
                    RecordService.getInstance().recordEvent(RecordLevel.LOG_INFO, "userBack", new String[]{"type", "homeBack"});
                    MyToygerActivity.this.onErrorCode(ZcodeConstants.ZCODE_USER_BACK);
                    MyToygerActivity.super.onBackPressed();
                }

                public void onCancel() {
                }
            });
        }
    }

    @SuppressLint("WrongConstant")
    private void showMessageBox(int titleResId, int messageResId, int posBtnResId, int negBtnResId, final MyToygerActivity.MessageBoxCB messageBoxCB) {
        this.btnClose.setEnabled(false);
        CommAlertOverlay commAlertOverlay = (CommAlertOverlay)this.findViewById(R.id.message_box_overlay);
        if (null != commAlertOverlay) {
            if (titleResId > 0) {
                commAlertOverlay.setTitleText(this.getString(titleResId));
            }

            if (messageResId > 0) {
                commAlertOverlay.setMessageText(this.getString(messageResId));
            }

            if (negBtnResId > 0) {
                commAlertOverlay.setButtonType(true);
                commAlertOverlay.setCancelText(this.getString(negBtnResId));
            } else {
                commAlertOverlay.setButtonType(false);
            }

            if (posBtnResId > 0) {
                commAlertOverlay.setConfirmText(this.getString(posBtnResId));
            }

            commAlertOverlay.setVisibility(0);
            this.pauseFaceScanProcess(true);
            commAlertOverlay.setCommAlertOverlayListener(new CommAlertOverlay.CommAlertOverlayListener() {
                public void onCancel() {
                    MyToygerActivity.this.btnClose.setEnabled(true);
                    if (null != messageBoxCB) {
                        MyToygerActivity.this.pauseFaceScanProcess(false);
                        messageBoxCB.onCancel();
                    }

                }

                public void onConfirm() {
                    MyToygerActivity.this.btnClose.setEnabled(true);
                    if (null != messageBoxCB) {
                        MyToygerActivity.this.pauseFaceScanProcess(false);
                        messageBoxCB.onOK();
                    }

                }
            });
        }

    }

    private interface MessageBoxCB {
        void onOK();

        void onCancel();
    }
}